package main

import (
	"encoding/json"
	"log"
	"net"
	"net/http"
	"net/rpc"

	"rtsp1/source/server"
)

var (
	openReply = server.Reply{}
	client    = rpc.Client{}
)

const (
	RPCProtocol = "tcp"
	RPCAddress  = "127.0.0.1:8081"
)

var startRequest struct {
	Source string
}

type startRespose0 struct {
	Status  int
	Address string
	Pid     int
}

type startRespose1 struct {
	Status  int
	Message string
}

var stopReuqest struct {
	Pid int
}

type stopRespose struct {
	Status  int
	Message string
}

func init() {

}

func getIP() string {
	addrs, err := net.InterfaceAddrs()
	if err != nil {
		log.Println("get ip", err.Error())
		return ""
	}
	return addrs[0].String()
}

func handleStart(rw http.ResponseWriter, req *http.Request) {
	log.Println("get request on start", req.RemoteAddr)
	body := req.Body
	defer body.Close()

	//parse json
	err := json.NewDecoder(body).Decode(&startRequest)
	if err != nil {
		log.Println("json", err.Error())
		res := startRespose1{
			Status:  1,
			Message: "json err:" + err.Error(),
		}
		json.NewEncoder(rw).Encode(res)
		return
	}

	//get source and write the respose
	name := startRequest.Source
	err = client.Call("Server.Open", name, &openReply)
	if err != nil {
		log.Println(err.Error())
		resp := startRespose1{
			Status:  1,
			Message: err.Error(),
		}
		json.NewEncoder(rw).Encode(resp)
	} else {
		log.Printf("Open %s success!\naddress:%s\npid:%d",
			name,
			openReply.Address,
			openReply.Pid)

		resp := startRespose0{
			Status:  0,
			Address: openReply.Address,
			Pid:     openReply.Pid,
		}
		json.NewEncoder(rw).Encode(resp)
	}
}

func handleStop(rw http.ResponseWriter, req *http.Request) {
	log.Println("get request on stop", req.RemoteAddr)
	r := req.Body
	defer r.Close()

	//parse json
	err := json.NewDecoder(r).Decode(&stopReuqest)
	if err != nil {
		log.Println(req.RemoteAddr, err.Error())
		resp := stopRespose{
			Status:  1,
			Message: err.Error(),
		}
		json.NewEncoder(rw).Encode(resp)
		return
	}

	//get the pid and write the respose
	var reply string
	pid := stopReuqest.Pid
	err = client.Call("Server.Close", pid, &reply)
	if err != nil {
		log.Println(err.Error())
		resp := stopRespose{
			Status:  1,
			Message: err.Error(),
		}
		json.NewEncoder(rw).Encode(resp)
	} else {
		log.Printf("Close %s success!", reply)

		resp := stopRespose{
			Status:  0,
			Message: reply,
		}
		json.NewEncoder(rw).Encode(resp)
	}
}

func main() {
	//dial the rpc server
	c, err := rpc.DialHTTP(RPCProtocol, RPCAddress)
	if err != nil {
		log.Fatal(err.Error())
	}
	client = *c

	//register the handle
	http.HandleFunc("/start", handleStart)
	http.HandleFunc("/stop", handleStop)
	log.Println("Begin to server,listen on 8080")
	err = http.ListenAndServe(":8080", nil)
	if err != nil {
		log.Fatal(err.Error())
	}
}
